#include "AnaDef.h"
#include "XGLUtils.h"
#include "AliTRDdEdxBaseUtils.h"

void TRDafterTPCTOF(const TString fin)
{
  TFile * ff=new TFile(fin);
  //TTree *tt = (TTree*)ff->Get("tree");
  TTree *tt = (TTree*)ff->Get("t1");
  if(!tt){
    printf("no tt!!\n"); gDirectory->ls(); exit(1);
  }

  const Double_t tpc0s[]={0, -1, -2, -3};
  const Double_t tpc1s[]={ 3,  3,  3, 3};
  const Int_t ncut = sizeof(tpc0s)/sizeof(Double_t);

  TList *ll=new TList;

  TCanvas * cc=new TCanvas;
  gPad->SetLogx();
  gPad->SetLogz(0);

  gSystem->Exec("mkdir -p outplot/");

  for(Int_t ii=0; ii<ncut; ii++){
   
    const TString hn=Form("htrd%d",ii);
    const TString cut=Form("tpcele>%.1f && tpcele<%.1f && trdnch==6 && trdncls/trdnch>17 && abs(abs(eta)-0.7)<0.1 ", tpc0s[ii], tpc1s[ii]);

    TH2D * htrd = new TH2D(hn,Form("%s  TOF -3 3;", cut.Data()), 100, 0.3, 5, 100, 0, 5); ll->Add(htrd);
    htrd->GetXaxis()->SetTitle("TRD p (GeV/c)");
    htrd->GetYaxis()->SetTitle("TRD dE/dx+TR signal");

    AliTRDdEdxBaseUtils::BinLogX(htrd->GetXaxis());


    printf("cut: %s\n", cut.Data());
    tt->Draw(Form("trdsig:pTRD>>%s", hn.Data()),cut, "colz");

    cc->Print(Form("outplot/%s.eps", htrd->GetName()));

    TH2D *hnor = XGLUtils::NormalHist(htrd,50, kTRUE);    ll->Add(hnor);
    hnor->Draw("colz");
    
    cc->Print(Form("outplot/%s.eps", hnor->GetName()));

    //=============
    //=============

    const TString hadn = Form("hhad%d",ii);
    const TString hadc = cut + "&& ( abs(tpcproton)<3 ||  abs(tpcpion)<3 || abs(tpckaon)<3 )";

    TH2D * hhad = new TH2D(hadn,Form("%s  TOF -3 3;", hadc.Data()), 100, 0.3, 5, 100, 0, 5);; ll->Add(hhad);
    hhad->GetXaxis()->SetTitle("TRD p (GeV/c)");
    hhad->GetYaxis()->SetTitle("TRD dE/dx+TR signal");

    AliTRDdEdxBaseUtils::BinLogX(hhad->GetXaxis());

    printf("hadron cut: %s\n", hadc.Data());
    tt->Draw(Form("trdsig:pTRD>>%s", hadn.Data()),hadc, "colz");

    cc->Print(Form("outplot/%s.eps", hhad->GetName()));
  }

  TFile *fout=new TFile(Form("trdele.root"),"recreate");
  ll->Write();
  fout->Save();
  fout->Close();
  delete fout;
}

int main(int argc, char * argv[])
{
  for(Int_t ii=0; ii<argc; ii++){
    printf("%d: %s\n", ii, argv[ii]);
  }

  if(argc!=2){
    printf("argc!=4\n"); return 1;
  }

  TRDafterTPCTOF(argv[1]);

  return 0;
}
